package com.hxxy.wyp.petsLover.common.services.base.fronted.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hxxy.wyp.petsLover.common.entities.Good;
import com.hxxy.wyp.petsLover.common.entities.Orders;
import com.hxxy.wyp.petsLover.common.entities.ShopCart;
import com.hxxy.wyp.petsLover.common.entities.User;
import com.hxxy.wyp.petsLover.common.entities.vo.req.ShopCartVo;
import com.hxxy.wyp.petsLover.common.mapper.GoodMapper;
import com.hxxy.wyp.petsLover.common.mapper.OrdersMapper;
import com.hxxy.wyp.petsLover.common.mapper.ShopCartMapper;
import com.hxxy.wyp.petsLover.common.services.base.fronted.ShopCartService;
import com.hxxy.wyp.petsLover.exception.AppException;
import com.hxxy.wyp.petsLover.security.SecurityContextFrontUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @ClassName ShopCartServiceImpl
 * @Description TODO
 * @Author wyp
 * @Date 2023/2/11 18:48
 * @Version 1.0
 */
@Service
public class ShopCartServiceImpl extends ServiceImpl<ShopCartMapper, ShopCart> implements ShopCartService {
    @Resource
    SecurityContextFrontUser securityContextFrontUser;

    @Resource
    ShopCartMapper shopCartMapper;

    @Resource
    GoodMapper goodMapper;

    @Resource
    OrdersMapper ordersMapper;;

    @Override
    public List<ShopCart> getAllShopCart() {
        User userInfo = securityContextFrontUser.getUserInfo();
        List<ShopCart> shopCartList = shopCartMapper.selectList(new LambdaQueryWrapper<>(ShopCart.class).eq(ShopCart::getUserId, userInfo.getId()).eq(ShopCart::getIsCompute, "0"));
        return shopCartList.stream().map(shopCart -> {
            Good good = goodMapper.selectById(shopCart.getGoodId());
            List<String> picList = Arrays.stream(good.getPic().split(",")).collect(Collectors.toList());
            good.setPicList(picList);
            good.setPic(picList.get(0));
            shopCart.setGood(good);
            return shopCart;
        }).collect(Collectors.toList());
    }

    @Override
    public void updateNumberAndComputeMoney(ShopCartVo shopCartVo) {
        Long id = shopCartVo.getId();
        Long val = shopCartVo.getVal();
        ShopCart shopCart = shopCartMapper.selectById(id);
        double commodityPrice = shopCart.getCommodityPrice();
        double totalPrice = commodityPrice * val;
        shopCart.setCommoditySubtotal(totalPrice);
        shopCart.setCommodityNumber(val);
        shopCartMapper.updateById(shopCart);
    }

    @Override
    public void putShopCart(String id) {
        User userInfo = securityContextFrontUser.getUserInfo();
        ShopCart shopCart = shopCartMapper.selectOne(new LambdaQueryWrapper<>(ShopCart.class).eq(ShopCart::getUserId, userInfo.getId()).eq(ShopCart::getGoodId, id).eq(ShopCart::getIsCompute,"0"));
        if (shopCart != null) {
            shopCart.setCommodityNumber(shopCart.getCommodityNumber() + 1);
            shopCart.setCommoditySubtotal(shopCart.getCommodityNumber() * shopCart.getCommodityPrice());
            shopCartMapper.updateById(shopCart);
        } else {
            Good good = goodMapper.selectById(id);
            ShopCart shopCart1 = new ShopCart();
            shopCart1.setCommodityName(good.getGoodName());
            shopCart1.setCommodityPrice(good.getPrice());
            shopCart1.setCommodityNumber(1L);
            shopCart1.setCommoditySubtotal(good.getPrice());
            shopCart1.setGoodId(Long.parseLong(id));
            shopCart1.setUserId(userInfo.getId());
            shopCartMapper.insert(shopCart1);
        }
    }

    @Override
    public Orders produceOrder(List<ShopCart> shopCartList) {
        if (shopCartList.size()==0){
            throw new AppException("购物车为空！不能结算!");
        }
        Orders orders = new Orders();
        User userInfo = securityContextFrontUser.getUserInfo();
        String orderId = RandomUtil.randomNumbers(12);
        LocalDateTime purchaseTime = LocalDateTime.now();
        Long userId = userInfo.getId();
        StringBuffer shopCartId = new StringBuffer();
        AtomicReference<Double> OrderMoney= new AtomicReference<>(0.00);
        shopCartList.stream().peek(shopCart -> {
            shopCartId.append(shopCart.getId());
            shopCart.setIsCompute("1");
            if (shopCartList.size() - 1 != shopCartList.indexOf(shopCart)) {
                shopCartId.append(",");
            }
            OrderMoney.set(OrderMoney.get() + shopCart.getCommoditySubtotal());
            shopCartMapper.updateById(shopCart);
        }).collect(Collectors.toList());
        orders.setOrderId(Long.parseLong(orderId));
        orders.setOrderMoney(OrderMoney.get());
        orders.setOrderPurchaseTime(purchaseTime);
        orders.setShopCartId(shopCartId.toString());
        orders.setOrderUser(userInfo.getUserName());
        orders.setOrderPhone(userInfo.getPhone());
        orders.setOrderStatus("0");
        orders.setUserId(userId);
        orders.setIsEvoluted("0");
        orders.setIsSend("0");
        orders.setShopCarts(shopCartList);
        int insert = ordersMapper.insert(orders);
        return orders;
    }
}
